<template>
  <!-- 报警记录表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="150">
      <el-row>
        <el-col :span="12">
          <el-form-item label="报警时间" prop="alarmTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.alarmTime"
              placeholder="请输入报警时间"
              clearable
            />

            <span v-else>{{ formData.alarmTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报警等级" prop="alarmLevel">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.alarmLevel"
              placeholder="请选择报警等级"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('ScaAlarmLevel')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName(
                "ScaAlarmLevel",
                formData.alarmLevel
              )
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备" prop="equipId">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipId"
              placeholder="请输入设备主键"
              clearable
            />

            <span v-else
              >{{ formData.equipCode }}-{{ formData.equipName }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="equipTypeId">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipTypeId"
              placeholder="请输入设备类型"
              clearable
            />

            <span v-else>{{ formData.equipTypeName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="报警内容" prop="alarmName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.alarmName"
              placeholder="请输入报警内容"
              clearable
            />

            <span v-else>{{ formData.alarmName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="报警触发条件" prop="triggerCondition">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入报警触发条件"
              clearable
            />

            <span v-else>{{ conditionValue.join(",") }}</span>
          </el-form-item></el-col
        >
      </el-row>

      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="异常数据开始时间" prop="exceptionStartTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.exceptionStartTime"
              placeholder="请输入异常数据开始时间"
              clearable
            />

            <span v-else>{{ formData.exceptionStartTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="异常数据结束时间" prop="exceptionEndTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.exceptionEndTime"
              placeholder="请输入异常数据结束时间"
              clearable
            />

            <span v-else>{{ formData.exceptionEndTime }}</span>
          </el-form-item>
        </el-col> -->
      <!-- </el-row> -->
    </el-form>
    <el-table
      v-loading="loading"
      :data="contentList"
      highlight-current-row
      border
      max-height="250"
    >
      <el-table-column
        label="采集时间"
        prop="alarmTime"
        min-width="100"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="变量"
        prop="parameterName"
        min-width="100"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="数据"
        prop="data"
        min-width="100"
        show-overflow-tooltip
      >
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "ADMINSCAALARMRECORDADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  version: [],
  alarmTime: [],
  alarmLevel: [
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
  ],
  equipId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  equipCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipTypeId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  alarmId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  alarmCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  alarmName: [],
  alarmContent: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  triggerCondition: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  exceptionStartTime: [],
  exceptionEndTime: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  alarmTime: "",
  alarmLevel: "",
  equipId: "",
  equipName: "",
  equipCode: "",
  equipTypeId: "",
  equipTypeName: "",
  alarmId: "",
  alarmCode: "",
  alarmName: "",
  alarmContent: "",
  triggerCondition: "",
  exceptionStartTime: "",
  exceptionEndTime: "",
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  scaAlarmSettingDetails: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        alarmTime,
        alarmLevel,
        equipId,
        equipName,
        equipCode,
        equipTypeId,
        equipTypeName,
        alarmId,
        alarmCode,
        alarmName,
        alarmContent,
        triggerCondition,
        exceptionStartTime,
        exceptionEndTime,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        scaAlarmSettingDetails,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        alarmTime,
        alarmLevel,
        equipId,
        equipName,
        equipCode,
        equipTypeId,
        equipTypeName,
        alarmId,
        alarmCode,
        alarmName,
        alarmContent,
        triggerCondition,
        exceptionStartTime,
        exceptionEndTime,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        scaAlarmSettingDetails,
      });
      getConditionValue();
      getContentList();
      // if (formData.equipId) {
      //   getCollectList();
      // }
    }
  }
);

// 采集table数据
const contentList: any = ref([]);
const getContentList = () => {
  formData.alarmContent.split("\n").forEach((item, index) => {
    contentList.value.push({
      alarmTime: formData.alarmTime,
      parameterName: item.split("-")[0],
      data: item.split("-")[1],
    });
  });

  // contentList.value.push({
  //   alarmTime: formData.alarmTime,
  //   parameter: contentList.value[0].,
  //   alarmContent: formData.alarmContent,
  // })
};

// 报警条件

// dictionaryStore.filterDictName("ScaAlarmConditions", row.conditionValue);
const conditionValue = ref([]);
const getConditionValue = () => {
  formData.scaAlarmSettingDetails.forEach((item) => {
    conditionValue.value.push(
      item.parameterName +
        dictionaryStore.filterDictName(
          "ScaAlarmConditions",
          item.conditionValue
        ) +
        item.alarmValue
    );
  });
};

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.alarmTime = "";
  formData.alarmLevel = "";
  formData.equipId = "";
  formData.equipName = "";
  formData.equipCode = "";
  formData.equipTypeId = "";
  formData.equipTypeName = "";
  formData.alarmId = "";
  formData.alarmCode = "";
  formData.alarmName = "";
  formData.alarmContent = "";
  formData.triggerCondition = "";
  formData.exceptionStartTime = "";
  formData.exceptionEndTime = "";
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.scaAlarmSettingDetails = [];
  contentList.value = [];
  conditionValue.value = [];
}

const loading = ref(false);

/** 报警记录保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/iotadmin/scaalarmrecord/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
// ${formData.equipId}1808751001530413058
// 获取该设备的采集数据
const tableList = ref([]);
const getCollectList = async () => {
  await request({
    url: `/iotadmin/scaequipinfo/get/${formData.equipId}`,
    method: "get",
  })
    .then((res) => {
      if (res.code == 200) {
        tableList.value = res.data.scaEquipCollectionParams;
      }
    })
    .catch((error) => {});
};

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style scoped lang="scss"></style>
